<template>
	<div id="personalCenter">
		<el-tabs v-model="activeName">
			<el-tab-pane label="个人资料" name="first">
				<div class="left">
					<!-- http://localhost:2008/api/user/avator -->
					<el-upload
						class="avatar-uploader"
						action="https://img.oioweb.cn/api.php"
						:show-file-list="false"
						:data='files'
						accept='image/*'
						:on-success="handleAvatarSuccess"
						:before-upload="beforeAvatarUpload">
						<img v-if="imageUrl" :src="imageUrl" class="avatar">
						<i v-else class="el-icon-plus avatar-uploader-icon"></i>
						<el-button   class='changeAvator'><i class='el-icon-upload'></i>想换头像了？ 点我吧</el-button>
					</el-upload>
				</div>
				<div class="right">
					<el-form label-position="right" label-width="96px" :model="user">
						<el-form-item>
							<span >用<i class='marginHalf'></i>户<i class='marginHalf'></i>名</span>
							<el-input v-model="user.username" maxlength='15' show-word-limit></el-input>
						</el-form-item>
						<el-form-item>
							<span >用<i class='marginHalf'></i>户<i class='marginHalf'></i>组</span>
							<el-input v-model="user.role" disabled></el-input>
						</el-form-item>
						<el-form-item>
							<span>注册时间</span>
							<el-input v-model="user.create_time" disabled></el-input>
						</el-form-item>
						<el-form-item>
							<span>个人介绍</span>
							<el-input
								type="textarea"
								placeholder="填写个人介绍"
								v-model="user.motto"
								maxlength="150"
								show-word-limit
								:autosize="{ minRows: 3, maxRows: 5}">
							</el-input>
						</el-form-item>
						<el-form-item v-if='!githubLogin'>
							<span>新的密码</span>
							<el-input    placeholder="需要修改密码就输入新的密码"  maxlength='15' v-model="user.newPass" show-password></el-input>
						</el-form-item>
						<el-form-item v-if='!githubLogin'>
							<span>确认密码</span>
							<el-input  placeholder="再次输入新的密码"  maxlength='15' v-model="user.newPass2" show-password></el-input>
						</el-form-item>
						<el-form-item class='btns'>
							<el-button type="primary" @click='updateMyInfo()'> 修 改 </el-button>
						</el-form-item>
					</el-form>
				</div>
			</el-tab-pane>
			<el-tab-pane label="账号关联" name="second">
				<div class="nameCorrelation">
					<el-form label-position="right" label-width="96px" :model="user">
						<el-form-item label="邮箱">
							<el-input v-model="user.email" readonly></el-input>
							<el-button type="primary" @click='openDialog($event,"email")'>更 换</el-button>
						</el-form-item>
						<el-form-item label="手机">
							<el-input v-model="user.phone"  maxlength=11 readonly></el-input>
							<el-button type="primary" @click='openDialog($event,"phone")'>{{user.phone==''?'绑 定':'更 换'+'手机'}}</el-button>
						</el-form-item>
					</el-form>
				</div>
			</el-tab-pane>
		</el-tabs>	
		<el-dialog
			:title="dialogTitle"
			:visible.sync="dialogVisible"
			width="40%"
			:modal-append-to-body='false'
			@closed='closeDialog'>  
			<span class="dialog-footer">
				<el-form label-position="right" label-width="96px" :model="user">
					<el-form-item :label="'新'+dialogLabel">
						<el-input  v-model="user.contact" :maxlength='dialogTitle.indexOf("邮箱")>-1?50:11' show-word-limit @blur='checkInfo'></el-input>
					</el-form-item>
					<el-form-item label="验证码">
						<el-input v-model="user.code" maxlength=6></el-input>
						<el-button class='sendCodeBtn' :loading="loading" @click='sendCodeBy' :disabled='disabledSendCode'>
							<span v-show='countDown'>{{countDown+'秒后'}}</span>
							获取验证码
						</el-button>
					</el-form-item>
					<el-button type="primary" @click='updateContact' :disabled='disabledUpdate'>确 定</el-button>
					<el-button @click="dialogVisible = false">取 消</el-button>
				</el-form>
			</span>
		</el-dialog>
	</div>
</template>
<script>
	import {api} from '@/api/public'
	export default {
		name:'personalCenter',
		data() {
			return {
				imageUrl:sessionStorage.getItem('avator'),
				githubLogin:false,
				activeName: 'first',
				dialogVisible:false,
				dialogTitle:'',
				dialogType:'',
				dialogLabel:'',
				disabledSendCode:true,
				countDown:0,
				timer:null,
				loading:false,
				user:{
					username:sessionStorage.getItem('name'),
					email:sessionStorage.getItem('email'),
					role:sessionStorage.getItem('role'),
					create_time:sessionStorage.getItem('create_time'),
					motto:sessionStorage.getItem('motto'),
					phone:sessionStorage.getItem('phone'),
					newPass:'',
					newPass2:'',
					code:'',
					contact:''
				},
				files:{
					type:"huluxia" 
				}
			};
		},
		created(){
			let githubLogin=sessionStorage.getItem('githubLogin');
			if(githubLogin) this.githubLogin=true;
		},
		computed:{
			disabledUpdate(){
				let {code}=this.user;
				return this.disabledSendCode && code && code.length==6?false:true;
			}
		},
		methods: {
			closeDialog(){
				this.user.contact=this.user.code='';
				this.disabledSendCode=true;
			},
			async checkInfo(){
				let {contact}=this.user;
				let title=this.dialogLabel;
				let checkType=this.dialogType;
				if(checkType=='email'){
					let reg=/^([a-zA-Z\d])(\w|\-)+@[a-zA-Z\d]+\.[a-zA-Z]{2,4}$/;
					let isEmail=reg.test(contact);
					if(contact=='' || !isEmail) return this.disabledSendCode=true;
				}
				else{
					let isPhone=/^1[3456789]\d{9}$/.test(contact);
					if(contact=='' || !isPhone) return this.disabledSendCode=true;
				}
				let {count}=await api('post','user','checkInfo',{info:this.user.contact,type:checkType});
				if(count>0){
					this.info(`该${title}已被绑定，请重新填写~~~`,'w');
					this.disabledSendCode=true;
				}
				else this.disabledSendCode=false;
			},
			async sendCodeBy(){
				if(this.timer) this.info('请稍后再试~~~','w'); 
				else{
					this.loading=this.disabledSendCode=true;		
					let title=this.dialogTitle;
					let sendApi='sendCodeBy';
					let type='';
					if(title.indexOf('邮箱')>-1){
						sendApi+='Email';
						type=2;
					}
					else{
						sendApi+='Phone';
						title.indexOf('绑定手机')>-1?type=2:type=3;
					}
					let {contact}=this.user;
					let {success}=await api('post','user',sendApi,{contact:contact,type:type});
					setTimeout(()=>{
						this.loading=false;
					},400);
					if(success){
						this.info('验证码发送成功~~~');
						this.countDown=60;
						this.timer=setInterval(()=>{
							this.countDown--;
							if(this.countDown==0){
								clearInterval(this.timer);
								this.timer=null;
								this.disabledSendCode=false;
								api('delete','user','deleteCode',{contact:contact});
							}
						},1000);
					}
					else this.info('验证码发送失败~~~','e');
				}
			},
			async updateContact(){
				if(!this.timer) return  this.info('还没发送验证码','w');
				let {code}=this.user;
				if(!code) return  this.info('验证码为空','w');
				let title=this.dialogTitle;
				let type=this.dialogType;
				let {contact}=this.user;
				let {success}=await api('post','user','checkCode',{code:code,contact:contact});
				if(success){
					let {success}=await api('put','user','updateInfo',{info:contact,type:type});
					if(success){
						sessionStorage.setItem(type,contact);
						this.user[type]=contact;
						this.info('操作成功');
						clearInterval(this.timer);
						api('delete','user','deleteCode',{contact:contact});
						this.timer=this.countDown=this.dialogVisible=false;
					}
					else this.info('操作失败，请稍后再试','e');
				}
				else this.info('验证码错误','e');
			},
			beforeAvatarUpload(file) {
               let {type,size}=file;
				if(!type.match('image/')){
					this.info('上传的不是图片~~~','w');
					return false;	
				}
                let isLt3M = size / 1024 / 1024 < 3;
				if(!isLt3M){
					this.info('上传头像图片大小不能超过3MB!~~~','w');
					return false;
				}
				this.info('图片正在上传中');
			},
			async handleAvatarSuccess(res, file) {
				let {success}=await api('put','user','updateAvator',{avator:res.imgurl})
				if(success){
					this.$bus.$emit('changeAvator',res.imgurl);
					this.imageUrl = res.imgurl;
					sessionStorage.setItem('avator',res.imgurl),
					this.info('头像更换成功~~~');
					return;
				}
				this.info('头像更换失败~~~','e');
			},
			openDialog(e,type){
				let title=e.target.innerText;
				this.dialogTitle=title;
				this.dialogLabel=title.slice(2);
				this.dialogType=type;
				this.dialogVisible=true;
			},
			updateMyInfo(){
				this.$confirm('你确定要修改个人信息吗?', '提示', {
					confirmButtonText: '确定一定以及肯定',
					cancelButtonText: '再考虑考虑',
					type: 'warning'
				}).then(async () => {
					let password='';
					let {phone,newPass,newPass2,username,motto}=this.user;
					if(phone !='' && phone.length!=11) this.info('绑定的手机号有误，请重试~~~','w');
					else if(newPass &&  newPass.length<3 || newPass.length>15)
						this.info('密码的长度不能小于3个字符，不能超过15个字符!~~~','w');
					if(newPass && newPass===newPass2 )
						password=newPass;
					else if(newPass!=newPass2) return this.info('两次输入的密码不一致~~~','w');
					let obj={
						username:username,
						motto:motto,
						password:password
					}
					let {success}=await api('put','user','byUpdate',obj);
					if(success){
						this.info('修改成功~~~');
						sessionStorage.setItem('name',username);
						sessionStorage.setItem('motto',motto);
						this.$bus.$emit('changeName',username);
						newPass=newPass2='';
					}
					else this.info('修改失败，该用户名已经存在!~~~','e');
		    	}).catch(() => {});
			}
		},
		destroyed () {
			// bus.$off('imgCount');
		}
	}
</script>
<style scoped lang='stylus'>
#personalCenter{
	overflow: hidden;
	>>>.el-tabs{
		.el-tabs__item{
			font-size: 15px;
		}
		.el-tabs__content{
			padding-top:1em;
		}
	}
	>>> .avatar-uploader{
		.el-upload {
			cursor: pointer;
			position: relative;
		}
		.avatar{
			&:hover{
				border-color: #409EFF;
			}
		}
	}
	>>> .avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 178px;
		height: 178px;
		line-height: 178px;
		text-align: center;
	}
	.el-tabs{
		.changeAvator{
			color:#555;
			margin-top: 1em;
			font-size: 15px;
			i{
				font-size: 20px;
				margin-right: .4em;
			}
		}
		.left,.right{
			float: left;
			margin-top: 1em;
		}
		.left{
			width: 25%;
			margin-left: 3em;
			text-align: center;
			.avatar {
				width: 200px;
				height: 200px;
				display: block;
				border-radius: 50%;
				border: 1px dashed #d9d9d9;
				margin: 0 auto;
				box-shadow: 0px 0px 5px 2px powderblue;
			}
		}
		.right{
			.el-form-item__content{
				>span{
					margin-right:1em;
					font-size:15px;
				}
			}
		}
		.right,.nameCorrelation{
			width: 50%;
			.el-input,.el-textarea{
				width: 70%;
				display: inline-block;
			}
			>>>.el-input__count{
				background: none;
				bottom: -2px;
				font-size: 13px;
				right: 5px;
			}
		}
		.nameCorrelation{
			margin:0 auto;
		}
		@media (max-width: 1200px){
			.left,.right{
				float: none;
				margin:2.1em auto;
				margin-top: 0;
				width: 75%;
				text-align: center;

			}
		}
	}
	.el-dialog{
		.btns{
			margin-left: 0;
			text-align: center;
		}
		.btns >>>.el-form-item__content{
			margin-left: 0 !important;
		}
	}
}
@media (min-width: 1200px) and ( max-width: 1500px){
	#pane-first .right{
		margin-left: 4em;
	}
	#pane-first .right .el-input,.el-textarea {
		width: 110%;
	}
}
</style>